package com.trumeen.immichgallery.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.trumeen.immichgallery.model.AppSettings
import com.trumeen.immichgallery.model.ImageSwitchPeriod
import com.trumeen.immichgallery.model.ImageType
import com.trumeen.immichgallery.repository.AuthManager
import com.trumeen.immichgallery.repository.NetworkRepository
import com.trumeen.immichgallery.repository.SettingsDataStore
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class SettingsViewModel @Inject constructor(
    private val settingsDataStore: SettingsDataStore,
    private val authManager: AuthManager,
    private val networkRepository: NetworkRepository
) : ViewModel() {

    // 服务器设置状态
    private val _serverAddress = MutableStateFlow("http://192.168.3.18:2283/api/")
    val serverAddress: StateFlow<String> = _serverAddress.asStateFlow()

    private val _username = MutableStateFlow("201888400@qq.com")
    val username: StateFlow<String> = _username.asStateFlow()

    private val _password = MutableStateFlow("Cheery90!")
    val password: StateFlow<String> = _password.asStateFlow()

    private val _isAuthenticated = MutableStateFlow(false)
    val isAuthenticated: StateFlow<Boolean> = _isAuthenticated.asStateFlow()

    private val _isConnecting = MutableStateFlow(false)
    val isConnecting: StateFlow<Boolean> = _isConnecting.asStateFlow()

    // 图片设置状态
    private val _imageSwitchPeriod = MutableStateFlow(ImageSwitchPeriod.ONE_HOUR)
    val imageSwitchPeriod: StateFlow<ImageSwitchPeriod> = _imageSwitchPeriod.asStateFlow()

    private val _imageType = MutableStateFlow(ImageType.TODAY_IN_HISTORY)
    val imageType: StateFlow<ImageType> = _imageType.asStateFlow()

    private val _selectedPersonId = MutableStateFlow("")
    val selectedPersonId: StateFlow<String> = _selectedPersonId.asStateFlow()

    init {
        loadSettings()
    }

    private fun loadSettings() {
        viewModelScope.launch {
            // 加载应用设置
            settingsDataStore.appSettingsFlow.collect { settings ->
                _serverAddress.value = settings.serverAddress
                _username.value = settings.username
                _password.value = settings.password
                _imageSwitchPeriod.value = settings.imageSwitchPeriod
                _imageType.value = settings.imageType
                _selectedPersonId.value = settings.selectedPersonId
            }

            // 加载认证状态
            authManager.isAuthenticatedFlow.collect { authenticated ->
                _isAuthenticated.value = authenticated
            }
        }
    }

    fun updateServerAddress(address: String) {
        _serverAddress.value = address
    }

    fun updateUsername(username: String) {
        _username.value = username
    }

    fun updatePassword(password: String) {
        _password.value = password
    }

    fun updateImageSwitchPeriod(period: ImageSwitchPeriod) {
        _imageSwitchPeriod.value = period
    }

    fun updateImageType(imageType: ImageType) {
        _imageType.value = imageType
    }

    fun updateSelectedPersonId(personId: String) {
        _selectedPersonId.value = personId
    }

    fun login() {
        viewModelScope.launch {
            _isConnecting.value = true

            networkRepository.login(_serverAddress.value, _username.value, _password.value)
                .onSuccess { loginResponse ->
                    authManager.saveAuthState(
                        accessToken = loginResponse.accessToken,
                        refreshToken = loginResponse.refreshToken,
                        userId = loginResponse.userId,
                        serverAddress = _serverAddress.value
                    )
                    saveSettings()
                }
                .onFailure { error ->
                    // 错误处理在调用处处理
                }

            _isConnecting.value = false
        }
    }

    fun logout() {
        viewModelScope.launch {
            _isConnecting.value = true

            authManager.getAccessToken()?.let { token ->
                networkRepository.logout(token)
            }

            authManager.clearAuthState()
            _isConnecting.value = false
        }
    }

    fun testConnection() {
        viewModelScope.launch {
            _isConnecting.value = true

            networkRepository.testServerConnection(_serverAddress.value, _username.value, _password.value)
                .onSuccess {
                    // 成功处理在调用处处理
                }
                .onFailure { error ->
                    // 错误处理在调用处处理
                }

            _isConnecting.value = false
        }
    }

    fun saveSettings() {
        viewModelScope.launch {
            val settings = AppSettings(
                serverAddress = _serverAddress.value,
                username = _username.value,
                password = _password.value,
                imageSwitchPeriod = _imageSwitchPeriod.value,
                imageType = _imageType.value,
                selectedPersonId = _selectedPersonId.value
            )
            settingsDataStore.saveAppSettings(settings)
        }
    }
}